//this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


// TransferWnd.cpp : implementation file
//

//#include "stdafx.h"
#include "wintypes.h"
#include "emule.h"
#include "TransferWnd.h"

#include "muuli_wdr.h"

// CTransferWnd dialog

IMPLEMENT_DYNAMIC_CLASS(CTransferWnd,wxPanel)

BEGIN_EVENT_TABLE(CTransferWnd,wxPanel)

END_EVENT_TABLE()
  // handled in controls ProcessEvents()
  //  EVT_MENU(MP_SWITCHCTRL,CTransferWnd::SwitchUploadList)
#include <wx/splitter.h>
//IMPLEMENT_DYNAMIC(CTransferWnd, CDialog)
CTransferWnd::CTransferWnd(wxWindow* pParent /*=NULL*/)
	: wxPanel(pParent,CTransferWnd::IDD)
{
  SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));
  wxSizer* content=transferDlg(this,TRUE);
  content->Show(this,TRUE);

  wxSplitterWindow* split=(wxSplitterWindow*)FindWindow("splitterWnd");

  wxPanel* subContent1=new wxPanel(split,-1);
  subContent1->SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));
  wxSizer* subC1=transferTopPane(subContent1,TRUE);
  wxPanel* subContent2=new wxPanel(split,-1);
  subContent2->SetBackgroundColour(GetColour(wxSYS_COLOUR_WINDOW));
  wxSizer* subC2=transferBottomPane(subContent2,FALSE);

  split->SplitHorizontally(subContent1,subContent2);

  uploadlistctrl=(CUploadListCtrl*)FindWindowByName("uploadList");
  downloadlistctrl=(CDownloadListCtrl*)FindWindowByName("downloadList");
  queuelistctrl=(CQueueListCtrl*)FindWindowByName("uploadQueue");
  // let's hide the queue
  queueSizer->Remove(queuelistctrl);
  subC2->SetDimension(0,0,100,50);
  queueSizer->Layout();
  //subC2->Layout();
  queuelistctrl->Show(FALSE);

  windowtransferstate=1;
}

CTransferWnd::~CTransferWnd()
{
}

#if 0
BEGIN_MESSAGE_MAP(CTransferWnd, CResizableDialog)
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT,0,0xFFFF,OnToolTipNotify)
END_MESSAGE_MAP()
#endif

#if 0
BOOL CTransferWnd::OnInitDialog(){
	CResizableDialog::OnInitDialog();
	Localize();
	windowtransferstate = 1;
	uploadlistctrl.Init();
	downloadlistctrl.Init();
	queuelistctrl.Init();
	((CStatic*)GetDlgItem(IDC_DOWNLOAD_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_DIRECTDOWNLOAD), IMAGE_ICON, 16, 16, 0));
	((CStatic*)GetDlgItem(IDC_UPLOAD_ICO))->SetIcon((HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_UPLOAD), IMAGE_ICON, 16, 16, 0));

	AddAnchor(IDC_DOWNLOADLIST,TOP_LEFT,CSize(100, theApp.glob_prefs->GetSplitterbarPosition() ));
	AddAnchor(IDC_UPLOADLIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_QUEUELIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_UPLOAD_TEXT,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_UPLOAD_ICO,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
	AddAnchor(IDC_QUEUECOUNT,BOTTOM_LEFT);
	AddAnchor(IDC_TSTATIC1,BOTTOM_LEFT);

	// splitting functionality
	CRect rc,rcSpl,rcDown;

	GetWindowRect(rc);
	ScreenToClient(rc);

	rcSpl=rc; rcSpl.top=rc.bottom-100 ; rcSpl.bottom=rcSpl.top+5;rcSpl.left=55;
	m_wndSplitter.Create(WS_CHILD | WS_VISIBLE, rcSpl, this, IDC_SPLITTER);
	SetInitLayout();

	// create tooltip
	m_ttip.Create(this);
	m_ttip.SetDelayTime(TTDT_AUTOPOP, 20000);
	m_ttip.SetDelayTime(TTDT_INITIAL, theApp.glob_prefs->GetToolTipDelay()*1000);
	m_ttip.SendMessage(TTM_SETMAXTIPWIDTH, 0, SHRT_MAX); // recognize \n chars!
	m_ttip.AddTool(&downloadlistctrl);
	m_ttip.AddTool(&uploadlistctrl);
	m_iOldToolTipItemDown = -1;
	m_iOldToolTipItemUp = -1;
	m_iOldToolTipItemQueue = -1;

	return true;
}
#endif

void CTransferWnd::ShowQueueCount(uint32 number){
	char buffer[100];
	wxString fmtstr="%u (%u "+ GetResString(IDS_BANNED).MakeLower() +")";
	sprintf(buffer,fmtstr.GetData(),number,theApp.uploadqueue->GetBanCount());
	wxStaticCast(FindWindowByName("clientCount"),wxStaticText)->SetLabel(buffer);
	//this->GetDlgItem(IDC_QUEUECOUNT)->SetWindowText(buffer);
}

#if 0
void CTransferWnd::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_UPLOADLIST, uploadlistctrl);
	DDX_Control(pDX, IDC_DOWNLOADLIST, downloadlistctrl);
	DDX_Control(pDX, IDC_QUEUELIST, queuelistctrl);
}
#endif

void CTransferWnd::SetInitLayout() {
#if 0
		CRect rcDown,rcSpl,rcW;
		CWnd* pWnd;

		GetWindowRect(rcW);
		ScreenToClient(rcW);

		LONG splitpos=(theApp.glob_prefs->GetSplitterbarPosition()*rcW.Height())/100;

		pWnd = GetDlgItem(IDC_DOWNLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=splitpos-5;
		downloadlistctrl.MoveWindow(rcDown);
		
		pWnd = GetDlgItem(IDC_UPLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=rcW.bottom-20;
		rcDown.top=splitpos+20;
		uploadlistctrl.MoveWindow(rcDown);

		pWnd = GetDlgItem(IDC_QUEUELIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);
		rcDown.right=rcW.right-7;
		rcDown.bottom=rcW.bottom-20;
		rcDown.top=splitpos+20;
		queuelistctrl.MoveWindow(rcDown);

		rcSpl=rcDown;
		rcSpl.top=rcDown.bottom+4;rcSpl.bottom=rcSpl.top+5;rcSpl.left=95;
		m_wndSplitter.MoveWindow(rcSpl,true);

		DoResize(0);
#endif
}

void CTransferWnd::DoResize(int delta)
{
#if 0
	CSplitterControl::ChangeHeight(&downloadlistctrl, delta);
	CSplitterControl::ChangeHeight(&uploadlistctrl, -delta, CW_BOTTOMALIGN);
	CSplitterControl::ChangeHeight(&queuelistctrl, -delta, CW_BOTTOMALIGN);

	UpdateSplitterRange();

	Invalidate();
	UpdateWindow();
#endif
}

// setting splitter range limits
void CTransferWnd::UpdateSplitterRange()
{
#if 0
		CRect rcDown,rcUp,rcW,rcSpl;
		CWnd* pWnd;

		GetWindowRect(rcW);
		ScreenToClient(rcW);

		pWnd = GetDlgItem(IDC_DOWNLOADLIST);
		pWnd->GetWindowRect(rcDown);
		ScreenToClient(rcDown);

		pWnd = GetDlgItem(IDC_UPLOADLIST);
		pWnd->GetWindowRect(rcUp);
		ScreenToClient(rcUp);

		pWnd = GetDlgItem(IDC_QUEUELIST);
		pWnd->GetWindowRect(rcUp);
		ScreenToClient(rcUp);

		theApp.glob_prefs->SetSplitterbarPosition((rcDown.bottom*100)/rcW.Height());

		RemoveAnchor(IDC_DOWNLOADLIST);RemoveAnchor(IDC_UPLOADLIST);RemoveAnchor(IDC_QUEUELIST);
		AddAnchor(IDC_DOWNLOADLIST,TOP_LEFT,CSize(100,theApp.glob_prefs->GetSplitterbarPosition() ));
		AddAnchor(IDC_UPLOADLIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);
		AddAnchor(IDC_QUEUELIST,CSize(0,theApp.glob_prefs->GetSplitterbarPosition()),BOTTOM_RIGHT);

		m_wndSplitter.SetRange(rcDown.top+50 , rcUp.bottom-40);
#endif
}


#if 0
LRESULT CTransferWnd::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{

	switch (message) {
		// arrange transferwindow layout
		case WM_PAINT:
			if (m_wndSplitter) {
				CRect rcDown,rcSpl,rcW;
				CWnd* pWnd;


				GetWindowRect(rcW);
				ScreenToClient(rcW);

				pWnd = GetDlgItem(IDC_DOWNLOADLIST);
				pWnd->GetWindowRect(rcDown);
				ScreenToClient(rcDown);

				if (rcW.Height()>0) {
					// splitter paint update
					rcSpl=rcDown;
					rcSpl.top=rcDown.bottom+8;rcSpl.bottom=rcSpl.top+5;rcSpl.left=95;
					GetDlgItem(IDC_UPLOAD_TEXT)->MoveWindow(30,rcSpl.top-5,90,16);
					GetDlgItem(IDC_UPLOAD_ICO)->MoveWindow(10,rcSpl.top-5,16,16);
					m_wndSplitter.MoveWindow(rcSpl,true);
					UpdateSplitterRange();
				}
			}
			break;
		case WM_NOTIFY:
			if (wParam == IDC_SPLITTER)
			{	
				SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
				DoResize(pHdr->delta);
			}
			break;
		case WM_WINDOWPOSCHANGED : 
			{
				CRect rcW;
				GetWindowRect(rcW);
				ScreenToClient(rcW);

				if (m_wndSplitter && rcW.Height()>0) Invalidate();
				break;
			}
		case WM_SIZE:
			if (m_wndSplitter) {
				CRect rcDown,rcSpl,rcW;
				CWnd* pWnd;

				GetWindowRect(rcW);
				ScreenToClient(rcW);

				if (rcW.Height()>0){
					pWnd = GetDlgItem(IDC_DOWNLOADLIST);
					pWnd->GetWindowRect(rcDown);
					ScreenToClient(rcDown);

					long splitpos=(theApp.glob_prefs->GetSplitterbarPosition()*rcW.Height())/100;

					rcSpl.right=rcDown.right;rcSpl.top=splitpos+10;rcSpl.bottom=rcSpl.top+5;rcSpl.left=95;
					m_wndSplitter.MoveWindow(rcSpl,true);
				}

			}
			break;
	}
	return CDialog::DefWindowProc(message, wParam, lParam);
}
#endif

#if 0
// CTransferWnd message handlers
BOOL CTransferWnd::PreTranslateMessage(MSG* pMsg)
{
	// handle tooltip updating, when mouse is moved from one item to another
	if (pMsg->message== WM_MOUSEMOVE)
		UpdateToolTips();

	// relay mouse events to tooltip control
	if (pMsg->message== WM_LBUTTONDOWN || pMsg->message== WM_LBUTTONUP || pMsg->message== WM_MOUSEMOVE)
		m_ttip.RelayEvent(pMsg);

	return CResizableDialog::PreTranslateMessage(pMsg);
}
#endif

void CTransferWnd::UpdateToolTips(void)
{
#if 0
	int sel = GetItemUnderMouse(&downloadlistctrl);
	if (sel != -1)
	{
		if (sel != m_iOldToolTipItemDown)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemDown = sel;
			return;
		}
	}
	int sel2 = GetItemUnderMouse(&uploadlistctrl);
	if (sel2 != -1)
	{
		if (sel2 != m_iOldToolTipItemUp)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemUp = sel2;
			return;
		}
	}
/* no tooltips needed ATM
	int sel3 = GetItemUnderMouse(&queuelistctrl);
	if (sel3 != -1)
	{
		if (sel3 != m_iOldToolTipItemQueue)
		{
			if (m_ttip.IsWindowVisible())
				m_ttip.Update();
			m_iOldToolTipItemQueue = sel3;
		}
	}
*/
	if (sel == -1 && sel2 == -1 /*&& sel3 != -1*/)
		m_ttip.Pop();

#endif
}

int CTransferWnd::GetItemUnderMouse(wxListCtrl* ctrl)
{
#if 0
	CPoint pt;
	::GetCursorPos(&pt);
	ctrl->ScreenToClient(&pt);
	LVHITTESTINFO hit, subhit;
	hit.pt = pt;
	subhit.pt = pt;
	ctrl->SubItemHitTest(&subhit);
	int sel = ctrl->HitTest(&hit);
	if (sel != LB_ERR && (hit.flags & LVHT_ONITEM))
	{
		if (subhit.iSubItem == 0)
			return sel;
	}
	return LB_ERR;
#endif
}

#if 0
BOOL CTransferWnd::OnToolTipNotify(UINT id, NMHDR *pNMH, LRESULT *pResult)
{
	TOOLTIPTEXT *pText = (TOOLTIPTEXT *)pNMH;
	int control_id = ::GetDlgCtrlID((HWND)pNMH->idFrom);
	if (!control_id)
		return FALSE;
	CString info;
	if (control_id == IDC_DOWNLOADLIST)
	{
		if (downloadlistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&downloadlistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		// build info text and display it
		CtrlItem_Struct* content = (CtrlItem_Struct*)downloadlistctrl.GetItemData(sel);
		if (content->type == 1) // for downloading files
		{
			CPartFile* partfile = (CPartFile*)content->value;
			CString strHash;
			strHash.Format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			partfile->GetFileHash()[0],partfile->GetFileHash()[1],partfile->GetFileHash()[2],partfile->GetFileHash()[3],partfile->GetFileHash()[4],partfile->GetFileHash()[5],partfile->GetFileHash()[6],partfile->GetFileHash()[7],
			partfile->GetFileHash()[8],partfile->GetFileHash()[9],partfile->GetFileHash()[10],partfile->GetFileHash()[11],partfile->GetFileHash()[12],partfile->GetFileHash()[13],partfile->GetFileHash()[14],partfile->GetFileHash()[15]);

			CTime t(partfile->GetFileDate());
			char lsc[50]; char compl[50]; char buffer[20];

			CastItoXBytes(partfile->GetCompletedSize(),lsc);
			CastItoXBytes(partfile->GetFileSize() ,buffer);
			sprintf(compl,"%s/%s",lsc,buffer);

			if (partfile->lastseencomplete==NULL) sprintf(lsc,GetResString(IDS_UNKNOWN).MakeLower() ); else
			sprintf(lsc,partfile->lastseencomplete.Format( "%A, %x, %X"));

			float availability = 0;
			if(partfile->GetPartCount() != 0) {
				availability = partfile->GetAvailablePartCount() * 100 / partfile->GetPartCount();
			}
			info.Format(GetResString(IDS_DL_FILENAME)+": %s (%d %s)\n"
				+GetResString(IDS_DATE)+": %s - "+ GetResString(IDS_FD_HASH) +" %s\n"
				+GetResString(IDS_PARTINFOS)+
				GetResString(IDS_PARTINFOS2)+"\n%s",
						partfile->GetFileName(), partfile->GetFileSize(),GetResString(IDS_BYTES),
						t.Format("%A, %B %d, %Y"), strHash,
						partfile->GetPartMetFileName(), partfile->GetPartCount(),GetResString(IDS_AVAIL),partfile->GetAvailablePartCount(),availability,
						(int)partfile->GetPercentCompleted(), compl, partfile->GetTransferingSrcCount(),
						GetResString(IDS_LASTSEENCOMPL)+" "+CString(lsc));
		}
		else if (content->type == 3 || content->type == 2) // for sources
		{
			CUpDownClient* client = (CUpDownClient*)content->value;
			in_addr server;
			server.S_un.S_addr = client->GetServerIP();

			info.Format(GetResString(IDS_NICKNAME)+" %s ("+GetResString(IDS_USERID)+": %u)\n"
				+GetResString(IDS_CLIENT)+" %s:%d\n"
				+GetResString(IDS_SERVER)+" %s:%d\n"
				+GetResString(IDS_SOURCEINFO),
						client->GetUserName(), client->GetUserID(),
						client->GetFullIP(), client->GetUserPort(), 
						inet_ntoa(server), client->GetServerPort(),
						/*client->GetAskedCount()*/0, client->GetAvailablePartCount());
			if (content->type == 2)
			{	// normal client
				info += GetResString(IDS_CLIENTSOURCENAME) + CString(client->GetClientFilename());
			}
			else
			{	// client asked twice
				info += GetResString(IDS_ASKEDFAF);
			}
		}
	}
	else if (control_id == IDC_UPLOADLIST)
	{
		if (uploadlistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&uploadlistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		CUpDownClient* client = (CUpDownClient*)uploadlistctrl.GetItemData(sel);
		CKnownFile* file = theApp.sharedfiles->GetFileByID(client->reqfileid);
		// build info text and display it
		info.Format(GetResString(IDS_USERINFO), client->GetUserName(), client->GetUserID());
		if (file)
		{
			info += GetResString(IDS_SF_REQUESTED) + CString(file->GetFileName()) + "\n";
			CString stat;
			stat.Format(GetResString(IDS_FILESTATS_SESSION)+GetResString(IDS_FILESTATS_TOTAL),
						file->statistic.GetAccepts(), file->statistic.GetRequests(), file->statistic.GetTransfered(),
						file->statistic.GetAllTimeAccepts(), file->statistic.GetAllTimeRequests(), file->statistic.GetAllTimeTransfered());
			info += stat;
		}
		else
		{
			info += GetResString(IDS_REQ_UNKNOWNFILE);
		}

	}
/*	no tooltips needed ATM
	else if (control_id == IDC_QUEUELIST)
	{
		if (queuelistctrl.GetItemCount() < 1)
			return FALSE;
		int sel = GetItemUnderMouse(&queuelistctrl);
		if (sel < 0 || sel == 65535)
			return FALSE;

		// build info text and display it
		CUpDownClient* client = (CUpDownClient*)uploadlistctrl.GetItemData(sel);
		in_addr server;
		server.S_un.S_addr = client->GetServerIP();

		info.Format("Nickname: %s (UserID: %u)\n"
					"Client %s:%d\n"
					"Server %s:%d\n"
					"AskedCount: %d - AvailablePartCount: %d",
					client->GetUserName(), client->GetUserID(),
					client->GetFullIP(), client->GetUserPort(), 
					inet_ntoa(server), client->GetServerPort(),
					client->GetAskedCount(), client->GetAvailablePartCount());

	}
*/
	m_strToolTip.ReleaseBuffer(); // release old used buffer
	m_strToolTip = info;
	pText->lpszText = m_strToolTip.GetBuffer(1);
	pText->hinst = NULL; // we are not using a resource
	PostMessage(WM_ACTIVATE);
	return TRUE;
}
#endif

void CTransferWnd::SwitchUploadList(wxCommandEvent& evt)
{
	if( windowtransferstate == 1){
#if 0
		uploadlistctrl.Hide();
		queuelistctrl.Visable();
		windowtransferstate = 0;
		GetDlgItem(IDC_UPLOAD_TEXT)->SetWindowText(GetResString(IDS_ONQUEUE));
#endif
		windowtransferstate=0;
		// hide the upload list
		queueSizer->Remove(uploadlistctrl);
		uploadlistctrl->Show(FALSE);
		queueSizer->Add(queuelistctrl,1,wxGROW|wxALIGN_CENTER_VERTICAL|wxALL,5);
		queuelistctrl->Show();
		queueSizer->Layout();
		wxStaticCast(FindWindowByName("uploadTitle"),wxStaticText)->SetLabel(GetResString(IDS_ONQUEUE));
	}
	else{
#if 0
		queuelistctrl.Hide();
		uploadlistctrl.Visable();
		windowtransferstate = 1;
		GetDlgItem(IDC_UPLOAD_TEXT)->SetWindowText(GetResString(IDS_TW_UPLOADS));
#endif
		windowtransferstate=1;
		// hide the queuelist
		queueSizer->Remove(queuelistctrl);
		queuelistctrl->Show(FALSE);
		queueSizer->Add(uploadlistctrl,1,wxGROW|wxALIGN_CENTER_VERTICAL|wxALL,5);
		uploadlistctrl->Show();
		queueSizer->Layout();
		wxStaticCast(FindWindowByName("uploadTitle"),wxStaticText)->SetLabel(GetResString(IDS_TW_UPLOADS));
	}
}

void CTransferWnd::Localize(){
#if 0
	GetDlgItem(IDC_DOWNLOAD_TEXT)->SetWindowText(GetResString(IDS_TW_DOWNLOADS));
	GetDlgItem(IDC_UPLOAD_TEXT)->SetWindowText(GetResString(IDS_TW_UPLOADS));
	GetDlgItem(IDC_TSTATIC1)->SetWindowText(GetResString(IDS_TW_QUEUE));

	downloadlistctrl.CreateMenues();
	downloadlistctrl.Localize();
	uploadlistctrl.Localize();
	queuelistctrl.Localize();
#endif
}
